//设置根路径
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

//封装一个函数
const tb = document.querySelector('#tb');
const form = document.querySelector('#bookForm');
const btns = document.querySelector('#btnSec');
const renderBooks = () => {
  axios.get('/api/getbooks').then(({ data: res }) => {
    const { data } = res
    console.log(res);
    const html = data.map(item => {
      return ` <tr>
                  <td>${item.id}</td>
                  <td>${item.bookname}</td>
                  <td>${item.author}</td>
                  <td>${item.publisher}</td>
                  <td><a href="#" data-id="${item.id}">删除</a></td>
                </tr>`
    }).join('')
    tb.innerHTML = html
  })
}
//页面加载渲染函数
renderBooks()
//添加
form.addEventListener('submit', function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true })
  axios.post('/api/addbook', data).then(({ data: res }) => {
    // console.log(res);
    if (res.status !== 201) return alert(res.msg)
    alert(res.msg)
    this.reset()
    renderBooks()
  })
})
//删除
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    // console.log(1);
    //获取自定义属性id
    let id = e.target.dataset.id
    // console.log(id);
    //发起删除请求
    // axios.get('/api/delbook', { params: { id } }).then(({ data: res }) => {
    axios.get('/api/delbook?id=' + id).then(({ data: res }) => {
      renderBooks()
    })
  }
});
//筛选
btns.addEventListener('click', function () {
  const bookname = document.querySelector('input[name=bookname]').value
  const author = document.querySelector('input[name=auther]').value
  const publisher = document.querySelector('input[name=publisher]').value
  console.log();

});